package com.cardone.persistent.support;

import com.cardone.context.ContextHolder;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 冗余更新
 * Created by Administrator on 2014/11/1.
 */
public class RedundancyUpdateAction implements UpdateAction {
    @Setter
    @Getter
    private String[] names;

    @Setter
    private String findSqlId = "/platform/findRedundancyByCode";

    @Setter
    private String updateSqlId = "/platform/updateRedundancyByCode";

    /*  updateTableName,updateFieldName,updateForeignKeyName,dataTableName,dataPrimaryKeyName
        SELECT `D`.`${dataPrimaryKeyName}`, `D`.`${dataFieldName}` FROM `${dataTableName}` AS `D` WHERE EXISTS (SELECT 1 FROM `${updateTableName}` AS `U` WHERE `U`.`${updateForeignKeyName}` = `D`.`${dataPrimaryKeyName}` AND `U`.`${updateFieldName}` <> `D`.`${dataFieldName}`)
        SELECT `D`.`ID`, `D`.`CODE` FROM `c1_dictionary_TYPE` AS `D` WHERE EXISTS (SELECT 1 FROM `c1_dictionary` AS `U` WHERE `U`.`TYPE_Id` = `D`.`ID` AND `U`.`TYPE_CODE` <> `D`.`CODE`)
        UPDATE `${updateTableName}` SET `${updateFieldName}` = :updateField WHERE `${updateForeignKeyName}` = :updateForeignKey and `${updateFieldName}` <> :updateField
    */
    @Setter
    private Map<String, Object> model;

    @Setter
    @Getter
    private List<RedundancyUpdateAction> children;

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void run() {
        JdbcTemplateSupport jdbcTemplateSupport = ContextHolder.getBean(JdbcTemplateSupport.class);

        List<Map<String, Object>> updateMapList = jdbcTemplateSupport.findList(this.findSqlId, this.model);

        if (CollectionUtils.isEmpty(updateMapList)) {
            return;
        }

        jdbcTemplateSupport.batchUpdate(this.updateSqlId, this.model, updateMapList);

        if (CollectionUtils.isEmpty(this.children)) {
            return;
        }

        for (RedundancyUpdateAction redundancyUpdateAction : this.children) {
            redundancyUpdateAction.run();
        }
    }
}
